<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getAdgroup($database, $user) {
	$campaignIdTempArray = [];
	$campaignIdList = $database->query("SELECT `campaignId`, `campaignName` FROM cfg_campaign where `companyId` = '{$user['companyId']}' AND `userId` = '{$user['userid']}'");
	if(is_array($campaignIdList)){
		foreach ($campaignIdList as $value) {
			array_push($campaignIdTempArray, $value['campaignId']);
		}
	}
	$adgroupIdArray = [];
	$campaignIdChunk = array_chunk($campaignIdTempArray, 100);
	foreach ($campaignIdChunk as $value) {
		$response = HttpPost('https://api.baidu.com/json/sms/service/AdgroupService/getAdgroup', json_encode([
			'header'=>['username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token']],
			'body'=> [
        "ids"=> $value,
        "idType"=> 3,
        "adgroupFields"=>[
            "adgroupId",
            "adgroupName",
            "campaignId",
            "pause",
            "maxPrice",
            "negativeWords",
            "exactNegativeWords",
            "status"
        ]
			]
		]));
		$bodyArray = json_decode($response, true);
		if(is_array($bodyArray['body']['data'])) {
			foreach ( $bodyArray['body']['data'] as $value ) {
				array_push($adgroupIdArray, $value['adgroupId']);
				$negativeWords = serialize($value['negativeWords']);
				$exactNegativeWords = serialize($value['exactNegativeWords']);
				$campaignName = getArrayValue($campaignIdList, $value['campaignId'], 'campaignId', 'campaignName', null);
				$res = $database->query("select id from cfg_adgroup where `companyId` = '{$user['companyId']}' AND `adgroupId` = '{$value['adgroupId']}' LIMIT 1");
				if( isset($res[0]['id']) ) {
					$database->query( " UPDATE cfg_adgroup SET `contact` = '{$user['contact']}', `customerid` = '{$user['customerid']}',  `maxPrice` = '{$value['maxPrice']}', `datatime` = NOW(), `campaignName` = '{$campaignName}', `adgroupName` = '{$value['adgroupName']}', 
					  `negativeWords` = '{$negativeWords}', `exactNegativeWords` = '{$exactNegativeWords}', `status` = '{$value['status']}' WHERE id = '{$res[0]['id']}'; ");
				} else {
					$database->query("INSERT INTO cfg_adgroup ( `companyId`, `userType`, `userId`, `customerid`, `contact`, `bazaarId`, `maxPrice`, `datatime`, `campaignId`, `campaignName`, `adgroupId`, `adgroupName`, `negativeWords`, `exactNegativeWords`, `status` ) values (
						'{$user['companyId']}', 1, '{$user['userid']}', '{$user['customerid']}', '{$user['contact']}', '{$user['bazaarId']}', '{$value['maxPrice']}', NOW(), '{$value['campaignId']}', '{$campaignName}', '{$value['adgroupId']}', '{$value['adgroupName']}',
						'{$negativeWords}', '{$exactNegativeWords}', '{$value['status']}') " );
				}
			}
		}
	}
	if(count($adgroupIdArray) > 0) {
		$adgroupIdStr = implode(',', $adgroupIdArray);
		$database->query(" DELETE FROM cfg_adgroup WHERE `companyId` = '{$user['companyId']}' AND `userType` = 1 AND `userId` = {$user['userid']} AND `adgroupId` NOT IN ($adgroupIdStr); " );
	}
}

run(function() use ($argv) {
	showMessage('获取单元数据.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `customerid`, `contact`, `username`, `password`, `token`, `bazaarId` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'获取计划数据.' );
				getAdgroup($database, $user);
			});
		}
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');